<template>
  <el-dialog
    title="角色权限设置"
    v-model="visible"
    draggable
    overflow
    :width="1000"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <sk-tabs type="border-card">
      <el-tab-pane label="菜单权限">
        <div class="treeMain">
          <el-tree
            ref="menu"
            node-key="id"
            :data="menu.list"
            :default-checked-keys="menu.defaultchecked"
            :props="menu.props"
            show-checkbox
            @check-change="menuCheckChange"
          ></el-tree>
        </div>
      </el-tab-pane>
      <el-tab-pane label="部门权限">
        <div class="treeMain">
          <el-tree
            ref="department"
            node-key="id"
            :data="department.list"
            :default-checked-keys="department.defaultchecked"
            :props="department.props"
            show-checkbox
            @check-change="departmentCheckChange"
          ></el-tree>
        </div>
      </el-tab-pane>
      <el-tab-pane label="表格权限">
        <el-col :span="24">
          <sc-VxeTable
            ref="tablerole"
            :gridEvts="gridEvents"
            :gridOps="gridOps"
            :tablecode="'system_table_role'"
            :data="table_list"
          >
          </sc-VxeTable>
        </el-col>
      </el-tab-pane>
      <el-tab-pane label="列权限">
        <el-row style="height: 100%">
          <el-col :span="24">
            <div class="treeMain">
              <el-tree
                ref="column"
                node-key="id"
                :data="column.list"
                :default-checked-keys="column.defaultchecked"
                :props="column.props"
                show-checkbox
                @check-change="columnCheckChange"
              ></el-tree>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="接口权限">
        <el-row style="height: 100%">
          <el-col :span="12">
            <sc-VxeTable
              ref="apiyes"
              :gridEvts="gridEvents"
              :tablecode="'system_role_api'"
              :url="$API.system.api.list"
              :params="[
                {
                  'role.role_id': {
                    type: 'in',
                    value: [this.form.role_id],
                    whereType: 'whereDoesntHave',
                  },
                },
                { is_visit: 1 },
              ]"
            >
            </sc-VxeTable>
          </el-col>
          <el-col :span="12">
            <sc-VxeTable
              ref="apino"
              :gridEvts="gridEvents"
              :tablecode="'system_role_api_yes'"
              :url="$API.system.api.list"
              :params="{ 'role.role_id': { type: 'in', value: [this.form.role_id] } }"
            >
            </sc-VxeTable>
          </el-col>
        </el-row>
      </el-tab-pane>
      <!-- <el-tab-pane label="控制台">
				<el-form label-width="100px" label-position="left">
					<el-form-item label="控制台视图">
						<el-select v-model="dashboard" placeholder="请选择">
							<el-option v-for="item in dashboardOptions" :key="item.value" :label="item.label"
								:value="item.value">
								<span style="float: left">{{
									item.label
								}}</span>
								<span style="
										float: right;
										color: #8492a6;
										font-size: 12px;
									">{{ item.views }}</span>
							</el-option>
						</el-select>
						<div class="el-form-item-msg">
							用于控制角色登录后控制台的视图
						</div>
					</el-form-item>
				</el-form>
			</el-tab-pane> -->
    </sk-tabs>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
  <skBrowserChoose
    v-model="choosetable"
    :name="'table_bowser'"
    :params="getParams"
    @close="choosetable = false"
    @select="addtable"
  >
  </skBrowserChoose>
</template>

<script>
import skBrowserChoose from "@/components/skBrowserChoose";
import { http } from "@/utils/request";
export default {
  components: { skBrowserChoose },
  emits: ["success", "closed"],
  data() {
    return {
      visible: false,
      isSaveing: false,
      choosetable: false,
      table_list: [],
      form: {
        role_id: 0,
        menu_ids: [],
        department_ids: [],
        column_ids: [],
        table_ids: [],
      },
      menu: {
        list: [],
        defaultchecked: [],
        checked: [],
        props: {
          label: (data) => {
            return data.meta.title + "[" + data.path + "]";
          },
        },
      },
      department: {
        list: [],
        defaultchecked: [],
        checked: [],
        props: {
          label: (data) => {
            let dept_name =
              data.financedepartment == null ? "" : data.financedepartment.name;
            return data.name + "[ " + dept_name + " ]";
          },
        },
      },
      column: {
        list: [],
        defaultchecked: [],
        checked: [],
        props: {
          label: (data) => {
            return (
              data.title + "[ " + data.gridtable.name + "_" + data.gridtable.code + " ]"
            );
          },
        },
      },

      dashboard: "0",
      dashboardOptions: [
        {
          value: "0",
          label: "数据统计",
          views: "stats",
        },
        {
          value: "1",
          label: "工作台",
          views: "work",
        },
      ],
      gridEvents: {
        enable: ({ button }) => {
          let api_ids = button.selectRecords.map(function (v) {
            return v.id;
          });
          this.$API.system.role.enableApi
            .post({ api_ids: api_ids, role_id: this.form.role_id })
            .then(() => {
              this.$refs.apiyes.refresh();
              this.$refs.apino.refresh();
            });
        },
        disable: ({ button }) => {
          let api_ids = button.selectRecords.map(function (v) {
            return v.id;
          });
          this.$API.system.role.disableApi
            .post({ api_ids: api_ids, role_id: this.form.role_id })
            .then(() => {
              this.$refs.apiyes.refresh();
              this.$refs.apino.refresh();
            });
        },
        add: () => {
          this.choosetable = true;
        },
        delete: async ({ button }) => {
          let api_ids = button.selectRecords.map(function (v) {
            return v.id;
          });
          return http
            .post(`${this.$API.system.role.table_right_btn.url}/../deletetable`, {
              ids: api_ids,
            })
            .then(() => {
              this.getTale();
            });
        },
      },
      gridOps: {
        height: 380,
        columns: [
          {
            field: "showFooter_auth",
            event: {
              select: ({ row }) => {
                this.saveTableRole(row);
              },
            },
          },
          {
            field: "export_auth",
            event: {
              select: ({ row }) => {
                this.saveTableRole(row);
              },
            },
          },
          {
            field: "setting_auth",
            event: {
              select: ({ row }) => {
                this.saveTableRole(row);
              },
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.getMenu();
    this.getDepartment();
    this.getAuthColumn();
    // this.getType();
  },
  methods: {
    async addtable(list) {
      var res = await this.$API.system.role.savetable.post({
        table_ids: list.map((v) => v.id),
        role_id: this.form.role_id,
      });
      if (res.code == 200) {
        this.getTale();
        this.choosetable = false;
      }
    },
    saveTableRole(role_table) {
      this.$nextTick(async () => {
        var res = await this.$API.system.role.saveroletable.post(role_table);
        if (res.code == 200) {
          this.getTale();
        }
      });
    },
    getParams() {
      return { role_id: this.form.role_id };
    },
    menuCheckChange() {
      var arr = this.CheckChange(this.$refs.menu);
      this.form.menu_ids = arr;
    },
    departmentCheckChange() {
      var arr = this.CheckChange(this.$refs.department);
      this.form.department_ids = arr;
    },
    columnCheckChange() {
      var arr = this.CheckChange(this.$refs.column);
      this.form.column_ids = arr;
    },
    CheckChange(ref) {
      //这里两个true，1. 是否只是叶子节点 2. 是否包含半选节点（就是使得选择的时候不包含父节点）
      let res = ref.getCheckedNodes(false, true);
      let arr = [];
      res.forEach((item) => {
        if (item.id != null) {
          arr.push(item.id);
        }
      });
      return arr;
    },
    //表单注入数据
    setData(role_id) {
      this.form.role_id = role_id;
      this.getTale();
      return this;
    },

    open() {
      this.getRoleMenu();
      this.getRoleDepartment();
      this.getRoleColumn();
      this.visible = true;
    },
    async submit() {
      this.isSaveing = true;
      setTimeout(() => {
        this.isSaveing = false;
      }, 1000);
      this.menuCheckChange();
      this.departmentCheckChange();
      this.columnCheckChange();
      var res = await this.$API.system.role.savePermission.post(this.form);
      if (res.code == 200) {
        this.$emit("success", this.form, this.mode);
        this.visible = false;
        this.isSaveing = false;
        this.$message.success("操作成功");
      }
    },
    //获取角色 对应菜单明细
    async getRoleMenu() {
      //所有的子元素找出来，为选中元素
      var res = await this.$API.system.role.menu.get(this.form);
      let parentids = [];
      let chooseId = [];
      for (let id in res.data) {
        parentids.push(res.data[id].parent_id);
      }
      for (let id in res.data) {
        let hasFind = parentids.find((parent_id) => parent_id == res.data[id].id);
        if (hasFind == undefined) {
          chooseId.push(res.data[id].id);
        }
      }
      this.menu.defaultchecked = chooseId;
    },
    //获取角色 对应菜单明细
    async getRoleDepartment() {
      //所有的子元素找出来，为选中元素
      var res = await this.$API.system.role.department.get(this.form);
      let parentids = [];
      let chooseId = [];
      for (let id in res.data) {
        parentids.push(res.data[id].parent_id);
      }
      for (let id in res.data) {
        let hasFind = parentids.find((parent_id) => parent_id == res.data[id].id);
        if (hasFind == undefined) {
          chooseId.push(res.data[id].id);
        }
      }
      this.department.defaultchecked = chooseId;
    },
    async getRoleColumn() {
      //所有的子元素找出来，为选中元素
      var res = await this.$API.system.role.column.get(this.form);
      let parentids = [];
      let chooseId = [];
      for (let id in res.data) {
        parentids.push(res.data[id].parent_id);
      }
      for (let id in res.data) {
        let hasFind = parentids.find((parent_id) => parent_id == res.data[id].id);
        if (hasFind == undefined) {
          chooseId.push(res.data[id].id);
        }
      }
      this.column.defaultchecked = chooseId;
    },
    async getMenu() {
      var res = await this.$API.system.menu.list.get();
      this.menu.list = res.data;
    },
    async getTale() {
      var res = await this.$API.system.role.table_right_btn.get({
        role_id: this.form.role_id,
      });
      this.table_list = res.data;
    },
    async getDepartment() {
      var res = await this.$API.system.department.treelist.get();
      this.department.list = res.data;
    },
    async getAuthColumn() {
      var res = await this.$API.system.tableconfig.authColumn.get();
      this.column.list = res.data;
    },
  },
};
</script>

<style scoped>
.treeMain {
  height: 380px;
  overflow: auto;
  border: 1px solid #dcdfe6;
}
</style>
